/**
 * Created by seeker910 on 2017/4/5.
 */
Rsd.define('Rsd.data.WebSocket', {
    extend: 'Rsd.common.Object',
    xtype: 'web-socket',
    /**
     * 通讯地址
     */
    wsUrl:'',
    isConnected:false,
    /**
     * 消息数据类型：text,json,application/json,rsd/message
     */
    contentType:'json',
    /**
     * 消息处理方法
     */
    messageHandler:'',
    "static":function __init()
    {
        window.WebSocket = window.WebSocket || window.MozWebSocket;
    },
    /*
     * */
    constructor: function WebSocket(config) {
        config = config || {};
        this.apply(config);
    },

    /*
    *
    * */
    onOpen: function onOpen(evt) {

        console.debug("CONNECTED");
    },
    /*
    * */
    onClose: function onClose(evt) {
        console.debug("DISCONNECTED");
    },

    /*
    * */
    onError: function onError(evt) {

        console.error(evt);
    },
    /*
    * */
    open:function open() {
        var me = this;
        //console.log(me.wsUrl);
        var websocket = new WebSocket(me.wsUrl);//创建时 即打开连接
        websocket.onopen = function (evt) {
            me.onOpen(evt);
            if(me._list)
            {
                for(var i in me._list)//待发送消息列表
                {
                    me.websocket.send(me._list[i]);
                }
                me._list = [];
            }
        };
        
        websocket.onclose = function (evt) {
            me.onClose(evt);
        };
        
        websocket.onmessage = function (evt) {
            console.log(evt);
            var data= null;
            if(evt && evt.data)
            {
                data = evt.data;
            }

            if(!data)
            {
                console.error('websocket message is null');
                return 
            }

            if(me.messageHandler)
            {
                //消息转化
                var _data = me.funApplyByIOC(me.messageConvert,[data]);
                //消息处理
                me.funApplyByIOC(me.messageHandler,[_data]); 
            }
            else 
            {
                console.error('no messageHandler functuon to handle',data);
            }
        };

        websocket.onerror = function (evt) {
            me.onError(evt);
        };
        //
        this.websocket = websocket;
    },
    /*
    * */
    send: function send(message) {

        var me = this;

        var _msg = message || ' ';

        if(Rsd.isObject(message))
        {
            _msg = ' ';
            for (var i in message)
            {
                if(message[i] != undefined)
                {
                    _msg += i + ':' +  message[i] + ' ';
                }

            }

        }

        if(me.websocket.readyState == 1)
        {
            me.websocket.send(Rsd.toString(_msg));
            return;
        }
        if(me.websocket.readyState == 0)
        {
            this._list = this._list ||[];
            this._list.push(Rsd.toString(_msg));
            return;
        }
        if(me.websocket.readyState == 3 || me.websocket.readyState == 4)
        {
            Rsd.alert('连接已关闭或不可用。');
            return;
        }


    },
    /*
    * */
    close:function close() {
        this.websocket.close();
    },
    /**
     * 
     * @param {*} msg 
     */
    messageConvert:function messageConvert(msg)
    {
        var me = this;

        if(me.contentType == 'json' ||  me.contentType == 'application/json' )
        {
            return Rsd.toJson(data);
        }
        
        if(me.contentType == 'rsd/message')
        {
            var arr = Rsd.decodeBase64(msg);
            var utf8Decoder = new TextDecoder('utf-8');
            var str = utf8Decoder.decode(arr).trim();
           
            //console.log(str,str.length);
            str = str.substring(str.indexOf('{')+1,str.lastIndexOf('}'));
            //console.log(str,str.length);
            var data ={};
            var list = str.split(',');
            for(var i=0;i< list.length;i++)
            {
                var item = list[i];
                if(Rsd.isEmpty(item))
                {
                    continue;
                }
                var key_value = item.split(':');
                var key = key_value[0];
                var value = key_value.length>1?key_value[1]:null;
                data[key.toFirstLowerCase()]=value;
            }
             
            return Rsd.create('Rsd.data.Message',data);
        }
 
        return  data;
    }
});